package com.kt.uokos.yimo.wx.controller;

import com.kt.uokos.yimo.dao.Footprint;
import com.kt.uokos.yimo.dao.Product;
import com.kt.uokos.yimo.service.FootprintService;
import com.kt.uokos.yimo.service.ProductService;
import com.kt.uokos.yimo.util.JacksonUtil;
import com.kt.uokos.yimo.util.ResponseUtil;
import com.kt.uokos.yimo.wx.annocation.LoginUser;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: TODO
 * @className: WxFootprintController.java
 * @author: Kang Hao
 * @date: 2022/4/27 14:32
 **/
@RestController
@RequestMapping("/wx/footprint/")
public class WxFootprintController {
    @Resource
    private FootprintService footprintService;

    @Resource
    private ProductService productService;

    @GetMapping("list")
    public Object list(@LoginUser Integer userId,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit){
        if (userId == null){
            return ResponseUtil.unlogin();
        }

        List<Footprint> footprintList = footprintService.queryByAddTime(userId, page, limit);

        List<Object> footprintVoList = new ArrayList<>(footprintList.size());
        for (Footprint footprint : footprintList) {
            Map<String, Object> c = new HashMap();
            c.put("id", footprint.getId());
            c.put("goodsId", footprint.getGoodsId());
            c.put("addTime", footprint.getAddTime());

            Product product = productService.queryByProId(footprint.getGoodsId());
            c.put("name", product.getName());
            c.put("brief", product.getBrief());
            c.put("picUrl", product.getPicUrl());
            c.put("retailPrice", product.getRetailPrice());

            footprintVoList.add(c);
        }
        return ResponseUtil.okList(footprintVoList, footprintList);

    }

    @PostMapping("delete")
    public Object delete(@LoginUser Integer userId,@RequestBody String body){
        if (userId == null){
            return ResponseUtil.unlogin();
        }

        if (body == null){
            return ResponseUtil.errs();
        }

        Integer footprintId = JacksonUtil.parseInteger(body, "id");
        if (footprintId == null) {
            return ResponseUtil.badArgument();
        }
        Footprint footprint = footprintService.queryById(footprintId);

        if (footprint == null) {
            return ResponseUtil.badArgumentValue();
        }
        if (!footprint.getUserId().equals(userId)) {
            return ResponseUtil.badArgumentValue();
        }

        footprintService.deleteById(footprintId);
        return ResponseUtil.ok();
    }



}
